﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using Google.API.Translate;
using System.Threading;
using MessageBox = System.Windows.Forms.MessageBox;

namespace SuperSearch
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }
        private static readonly TranslateClient TranslateClient = new TranslateClient();
        //private GSuggestions suggestions = new GSuggestions();

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.Enter:
                    {
                        Debug.WriteLine("->" + System.DateTime.Now.TimeOfDay);
                        //listBox1.Dispatcher.BeginInvoke(DispatcherPriority.DataBind, new test(UpdateResult));
                        textBoxTranslate.Text = String.Empty;
                        textBoxTranslate.Dispatcher.BeginInvoke(DispatcherPriority.DataBind, (ThreadStart)UpdateResult);
                        Debug.WriteLine("<-" + System.DateTime.Now.TimeOfDay);
                        break;
                    }
                case Key.Escape:
                    {
                        Close();
                        break;
                    }
                case Key.Back:
                    {
                        if (textBox1.Text.Length <= 3)
                        {
                            lstViewSuggestion.Items.Clear();
                            borderResult.Visibility = Visibility.Hidden;
                        }
                        else if (textBox1.Text.Length >= 3)
                        {
                            GSuggestions.QueryAsync(SecurityElement.Escape(textBox1.Text));
                        }
                        break;
                    }
                case Key.Up:
                    {
                        lstViewSuggestion.Focus();
                        break;
                    }
                case Key.Down:
                    {
                        lstViewSuggestion.Focus();
                        break;
                    }
                default:
                    {
                        if (textBox1.Text.Length >= 3)
                        {
                            GSuggestions.QueryAsync(SecurityElement.Escape(textBox1.Text));
                        }
                        break;
                    }
            }
        }

        void GSuggestionsOnComplete(ICollection<GSuggestions.Suggestion> suggestions)
        {
            lstViewSuggestion.Items.Clear();
            if (suggestions.Count > 0)
            {
                foreach (var suggestion in suggestions)
                {
                    lstViewSuggestion.Items.Add(suggestion.Text);
                }
                borderResult.Visibility = Visibility.Visible;
            }
            else
                borderResult.Visibility = Visibility.Hidden;
        }

        /// <summary>
        /// Updates the window location.
        /// </summary>
        private void UpdateWindowLocation()
        {
            //Windows1.Left = (SystemParameters.WorkArea.Width - ActualWidth) / 2;
        }

        //[MethodImpl(MethodImplOptions.Synchronized)]
        private void UpdateResult()
        {
            Debug.WriteLine("-->" + System.DateTime.Now.TimeOfDay);
            //textBoxTranslate.IsEnabled = false;
            try
            {
                //ThreadPool.QueueUserWorkItem(delegate { UpdateResult(); });
                //ThreadPool.QueueUserWorkItem(delegate { Thread.Sleep(4000); });
                //Thread.Sleep(1000);
                if (SuperSearch.Properties.Settings.Default.LanguageAutoDetect)
                {
                    Google.API.Language sourceLanguage;
                    textBoxTranslate.Text = TranslateClient.TranslateAndDetect(textBox1.Text,
                                    (Google.API.Language)Enum.Parse(typeof(Google.API.Language),
                                    SuperSearch.Properties.Settings.Default.LanguageSource),
                                    out sourceLanguage);
                }
                else
                {
                    textBoxTranslate.Text = TranslateClient.Translate(textBox1.Text,
                       (Google.API.Language)Enum.Parse(typeof(Google.API.Language), SuperSearch.Properties.Settings.Default.LanguageSource),
                       (Google.API.Language)Enum.Parse(typeof(Google.API.Language), SuperSearch.Properties.Settings.Default.LanguageDestination));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            Debug.WriteLine("<--" + System.DateTime.Now.TimeOfDay);
        }

        private void Windows1_Loaded(object sender, RoutedEventArgs e)
        {
            borderResult.Visibility = Visibility.Hidden;
            GSuggestions.OnComplete += GSuggestionsOnComplete;
            textBox1.Focus();
        }

        private void Windows1_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            UpdateWindowLocation();

            //foreach (var language in GetLanguages())
            //{
            //    var icon = new BitmapImage(new Uri(@"Resources/_1.ico", UriKind.Relative));
            //    var img = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(Properties.Resources.imgSE.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());

            //    var item = new MenuItem
            //                   {
            //                       Header = language,
            //                   };
            //    ((HeaderedItemsControl)menu1.Items[0]).Items.Add(item);
            //}
        }

        /// <summary>
        /// Gets the countries.
        /// </summary>
        /// <returns></returns>
        private static List<String> GetLanguages()
        {
            return Enum.GetNames(typeof(Google.API.Language)).ToList();
        }

        private void lstViewSuggestion_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.Enter:
                    {
                        textBox1.Text = lstViewSuggestion.SelectedValue.ToString();
                        textBox1.Select(textBox1.Text.Length, textBox1.Text.Length);
                        textBox1.Focus();
                        borderResult.Visibility = Visibility.Hidden;
                        break;
                    }
                case Key.Escape:
                    {
                        textBox1.Focus();
                        textBox1.Select(textBox1.Text.Length, textBox1.Text.Length);
                        borderResult.Visibility = Visibility.Hidden;
                        break;
                    }
            }
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            var frm = new Settings();
            frm.ShowDialog();
        }
    }
}
